package app.hzvmap.com.rangecontrol.acitvity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baoyz.actionsheet.ActionSheet;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;

import org.xutils.ex.DbException;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import app.hzvmap.com.rangecontrol.App;
import app.hzvmap.com.rangecontrol.R;
import app.hzvmap.com.rangecontrol.acitvity.Base.AppCompatBaseActivity;
import app.hzvmap.com.rangecontrol.service.InspectService;
import app.hzvmap.com.rangecontrol.utils.AppSetting;
import app.hzvmap.com.rangecontrol.utils.DateUtil;
import app.hzvmap.com.rangecontrol.utils.GPSUtils;
import app.hzvmap.com.rangecontrol.utils.MapUtil;
import app.hzvmap.com.rangecontrol.utils.camera.CameraCore;
import app.hzvmap.com.rangecontrol.utils.camera.CameraProxy;
import app.hzvmap.com.rangecontrol.views.X5ProgressWebView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import util.NativeUtil;

import static android.os.Environment.getExternalStorageDirectory;
import static android.view.View.GONE;

@ContentView(R.layout.activity_h5)
public class H5Activity extends AppCompatBaseActivity implements X5ProgressWebView.OnWebViewCallback, AMapLocationListener, CameraCore.CameraResult, EasyPermissions.PermissionCallbacks {
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.ACCESS_FINE_LOCATION"};
    private static final int RC_CAMERA_PERM = 123;
    private static final int RC_LOCATION_CONTACTS_PERM = 124;
    private static final int RC_SETTINGS_SCREEN = 125;
    private static final int RC_EXTERNAL_STORAGE = 126;
    private static final int RC_READ_PHONE_STATE = 127;
    //图片
    private final static int FILE_CHOOSER_RESULT_CODE = 128;
    //拍照
    private final static int FILE_CAMERA_RESULT_CODE = 129;

    public AMapLocationClient locationClient = null;


    private X5ProgressWebView wvH5;

    @ViewInject(R.id.llH5)
    private LinearLayout llH5;

    private ValueCallback<Uri> valueCallback;
    private ValueCallback<Uri[]> valuesCallback;


    private String capturePath = "";
    private CameraProxy cameraProxy;


    String imagePaths;
    Uri cameraUri;

    String compressPath = "";

    IX5WebChromeClient.CustomViewCallback customViewCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        setConfigCallback((WindowManager)getApplicationContext().getSystemService(Context.WINDOW_SERVICE));

        wvH5 = new X5ProgressWebView(this);
        LinearLayout.LayoutParams l
                = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        llH5.addView(wvH5, l);

        if (getIntent().getIntExtra("orientation", 0) == 1) {

            wvH5.setWebChromeClient(new X5WebChromeClient());
        }

        cameraProxy = new CameraProxy(this, this);
        setTheme(R.style.ActionSheetStyleiOS7);
        wvH5.addJavascriptInterface(this, "native");
        wvH5.setCallback(this);

        String url = getIntent().getStringExtra("url");
        if (TextUtils.isEmpty(url)) {
            Toast.makeText(H5Activity.this, "地址不存在!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        wvH5.loadUrl(url);

        if (AppSetting.getAppSetting(H5Activity.this).RUNSTATE.get() == 1) {
            App.getInstance().startService(new Intent(H5Activity.this, InspectService.class));
        }

        new Handler().postDelayed(new Runnable() {
            public void run() {
                cameraTask();
            }

        }, 1000);
    }


    @AfterPermissionGranted(RC_CAMERA_PERM)
    public void cameraTask() {
        if (EasyPermissions.hasPermissions(this, android.Manifest.permission.CAMERA)) {
            // Have permission, do the thing!
            locationAndContactsTask();
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_camera),
                    RC_CAMERA_PERM, android.Manifest.permission.CAMERA);
        }
    }

    @AfterPermissionGranted(RC_EXTERNAL_STORAGE)
    public void externalstorageTask() {
        String[] perms = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Have permissions, do the thing!
            readPhoneStateTask();
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_exstore_contacts),
                    RC_EXTERNAL_STORAGE, perms);
        }
    }

    @AfterPermissionGranted(RC_LOCATION_CONTACTS_PERM)
    public void locationAndContactsTask() {
        String[] perms = {android.Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Have permissions, do the thing!
            externalstorageTask();
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
                    RC_LOCATION_CONTACTS_PERM, perms);
        }
    }

    @AfterPermissionGranted(RC_READ_PHONE_STATE)
    public void readPhoneStateTask() {
        String[] perms = {android.Manifest.permission.READ_PHONE_STATE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // Have permissions, do the thing!
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(this, getString(R.string.rationale_read_phone_state),
                    RC_READ_PHONE_STATE, perms);
        }
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == RC_CAMERA_PERM) {
            locationAndContactsTask();
        } else if (requestCode == RC_LOCATION_CONTACTS_PERM) {
            externalstorageTask();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == RC_CAMERA_PERM) {
            locationAndContactsTask();
        } else if (requestCode == RC_LOCATION_CONTACTS_PERM) {
            externalstorageTask();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    protected void onResume() {

//        if (getIntent().getIntExtra("orientation", 0) == 0) {
//            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
//                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//            }
//        }

        super.onResume();
    }

    @Override
    public void onUrlCallback(String url) {
        if (url.contains("appback")) {
            finish();
        }
    }

    @Override
    public void onLoadCallback(String url, int status) {
        if (url.contains("appback")) {
            finish();
        }
        if (status == 0) {
            //head.setVisibility(View.VISIBLE);
            // callH5("javascript:headVisibility(0)");
        } else {
            // callH5("javascript:headVisibility(1)");
        }
    }

    @Override
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {
        this.valueCallback = uploadMsg;
        ActionSheet.createBuilder(this, getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("拍照", "相册")
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
                        if (isCancel) {
                            if (valueCallback != null) {
                                valueCallback.onReceiveValue(null);
                                valueCallback = null;
                            } else if (valuesCallback != null) {
                                valuesCallback.onReceiveValue(null);
                                valuesCallback = null;
                            }
                        }
                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {

                        compressPath = Environment
                                .getExternalStorageDirectory()
                                .getPath()
                                + "/fuiou_wmp/temp";
                        new File(compressPath).mkdirs();
                        compressPath = compressPath + File.separator
                                + "compress.jpg";

                        switch (index) {
                            case 0:
                                openCarcme();
                                break;
                            case 1:
                                chosePic();
                                break;
                        }
                    }
                }).show();
    }

    @Override
    public void onShowFileChooser(ValueCallback<Uri[]> uploadMsg) {
        this.valuesCallback = uploadMsg;
        // startActivityForResult(intent, 100);
        ActionSheet.createBuilder(this, getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("拍照", "相册")
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {
                        if (isCancel) {
                            if (valueCallback != null) {
                                valueCallback.onReceiveValue(null);
                                valueCallback = null;
                            } else if (valuesCallback != null) {
                                valuesCallback.onReceiveValue(null);
                                valuesCallback = null;
                            }
                        }
                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {

                        compressPath = Environment
                                .getExternalStorageDirectory()
                                .getPath()
                                + "/fuiou_wmp/temp";
                        new File(compressPath).mkdirs();
                        compressPath = compressPath + File.separator
                                + "compress.jpg";

                        switch (index) {
                            case 0:
                                openCarcme();
                                break;
                            case 1:
                                chosePic();
                                break;
                        }
                    }
                }).show();
    }

    /**
     * 检查SD卡是否存在
     *
     * @return
     */
    public final boolean checkSDcard() {
        boolean flag = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (!flag) {
            Toast.makeText(this, "请插入手机存储卡再使用本功能", Toast.LENGTH_SHORT).show();
        }
        return flag;
    }

    /**
     * 打开照相机
     */
    private void openCarcme() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
            File dir = new File(getExternalStorageDirectory(), "photo");
            this.capturePath = dir.getAbsolutePath() + "/temp_" + formatter.format(curDate) + ".jpg";
            if (!dir.exists()) {
                dir.mkdirs();
            }
            cameraProxy.getPhoto2Camera(capturePath);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡",
                    Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 本地相册选择图片
     */
    private void chosePic() {
        //FileUtils.delFile(compressPath);
        Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
        String IMAGE_UNSPECIFIED = "image/*";
        innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
        Intent wrapperIntent = Intent.createChooser(innerIntent, null);
        startActivityForResult(wrapperIntent, FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    public void onReceivedTitle(String title) {

    }

    @Override
    public void onReceivedError() {

    }


    public void setLocationOption(boolean isOnce) {

    }

    public void setConfigCallback(WindowManager windowManager) {
        try {
            Field field = WebView.class.getDeclaredField("mWebViewCore");
            field = field.getType().getDeclaredField("mBrowserFrame");
            field = field.getType().getDeclaredField("sConfigCallback");
            field.setAccessible(true);
            Object configCallback = field.get(null);
            if (null == configCallback) {
                return;
            }
            field = field.getType().getDeclaredField("mWindowManager");
            field.setAccessible(true);
            field.set(configCallback, windowManager);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public synchronized void releaseWebViews() {
        if (wvH5 != null) {
            try {
                if (wvH5.getParent() != null) {
                    ((ViewGroup) wvH5.getParent()).removeView(wvH5);
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                    wvH5.destroy();
                }
            } catch (IllegalArgumentException e) {

            }
            wvH5 = null;
        }
    }


    private boolean isOnce = false;
    private boolean isTrace = false;

    @JavascriptInterface
    public void getLocation() {
        if (!this.isTrace) {
            if (locationClient == null) {
                locationClient = new AMapLocationClient(this);
            }
            AMapLocationClientOption option = new AMapLocationClientOption();
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setOnceLocation(true);
            option.setMockEnable(false);
            option.setLocationCacheEnable(false);
            option.setSensorEnable(true);
            locationClient.setLocationOption(option);
            locationClient.setLocationListener(this);
            if (locationClient != null && !locationClient.isStarted()) {
                locationClient.startLocation();
            }
        }
        this.isOnce = true;
    }

    @JavascriptInterface
    public void startLocationChange() {
        this.isTrace = true;
        if (locationClient == null) {
            locationClient = new AMapLocationClient(this);
        }
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setInterval(5 * 1000);
        option.setMockEnable(false);
        option.setLocationCacheEnable(false);
        option.setSensorEnable(true);
        locationClient.setLocationOption(option);
        locationClient.setLocationListener(this);
        if (locationClient != null && !locationClient.isStarted()) {
            locationClient.startLocation();
        }
    }

    @JavascriptInterface
    public void stopLocationChange() {
        this.isTrace = false;
    }


    @JavascriptInterface
    public void appBack() {
        finish();
    }


    @JavascriptInterface
    public void logout() {
        AppSetting.getAppSetting(this).ACCOUNT.set("");
        AppSetting.getAppSetting(this).GUID.set("");
        AppSetting.getAppSetting(this).RUNSTATE.set(0);
        String url = AppSetting.getAppSetting(this).APPSERVER.get() + AppSetting.getAppSetting(this).APPLOGIN.get();

        wvH5.loadUrl(url);
    }

    @JavascriptInterface
    public void exit() {
        AppSetting.getAppSetting(this).APPLOGIN.set("");
        AppSetting.getAppSetting(this).APPHOME.set("");
        AppSetting.getAppSetting(this).APPSERVER.set("");
        AppSetting.getAppSetting(this).TRACKPORT.set(0);
        AppSetting.getAppSetting(this).TRACKSERVER.set("");
        AppSetting.getAppSetting(this).ACCOUNT.set("");
        AppSetting.getAppSetting(this).GUID.set("");
        AppSetting.getAppSetting(this).RUNSTATE.set(0);

        Intent intent = new Intent(H5Activity.this, SettingsActivity.class);
        startActivity(intent);
        finish();
    }

    @JavascriptInterface
    public void setAccount(String account, String guid) {
        AppSetting.getAppSetting(this).ACCOUNT.set(account);
        AppSetting.getAppSetting(this).GUID.set(guid);
    }

    @JavascriptInterface
    public void startInspection() {
        AppSetting.getAppSetting(this).RUNSTATE.set(1);
        UUID uuid = UUID.randomUUID();
        AppSetting.getAppSetting(this).INSPECTDAY.set(DateUtil.getNowDay());
        AppSetting.getAppSetting(this).PARTNUM.set(uuid.toString().replace("-", ""));
        App.getInstance().startService(new Intent(H5Activity.this, InspectService.class));
    }


    @JavascriptInterface
    public void endInspection() {
        App.getInstance().stopService(new Intent(H5Activity.this, InspectService.class));
        AppSetting.getAppSetting(this).RUNSTATE.set(0);
        AppSetting.getAppSetting(this).PARTNUM.set("");
    }

    @JavascriptInterface
    public int getInspectionState() {
        return AppSetting.getAppSetting(this).RUNSTATE.get();
    }

    @JavascriptInterface
    public void openMap(final double latx, final double laty, final String mAddress) {

        ActionSheet.createBuilder(this, getSupportFragmentManager())
                .setCancelButtonTitle("取消")
                .setOtherButtonTitles("高德地图", "百度地图", "腾讯地图")
                .setCancelableOnTouchOutside(true)
                .setListener(

                        new ActionSheet.ActionSheetListener() {
                            @Override
                            public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                            }

                            @Override
                            public void onOtherButtonClick(ActionSheet actionSheet, int index) {
                                switch (index) {
                                    case 0:
                                        if (MapUtil.isGdMapInstalled()) {
                                            MapUtil.openGaoDeNavi(H5Activity.this, 0, 0, null, latx, laty, mAddress);
                                        } else {
                                            //这里必须要写逻辑，不然如果手机没安装该应用，程序会闪退，这里可以实现下载安装该地图应用
                                            Toast.makeText(H5Activity.this, "尚未安装高德地图", Toast.LENGTH_SHORT).show();
                                            Uri uri = Uri.parse("market://details?id="+MapUtil.PN_GAODE_MAP);
                                            startActivity(new Intent(Intent.ACTION_VIEW, uri));
                                        }
                                        break;
                                    case 1:
                                        if (MapUtil.isBaiduMapInstalled()) {
                                            MapUtil.openBaiDuNavi(H5Activity.this, 0, 0, null, latx, laty, mAddress);
                                        } else {
                                            Toast.makeText(H5Activity.this, "尚未安装百度地图", Toast.LENGTH_SHORT).show();
                                            Uri uri = Uri.parse("market://details?id="+MapUtil.PN_BAIDU_MAP);
                                            startActivity(new Intent(Intent.ACTION_VIEW, uri));
                                        }
                                        break;
                                    case 2:
                                        if (MapUtil.isTencentMapInstalled()) {
                                            MapUtil.openTencentMap(H5Activity.this, 0, 0, null, latx, laty, mAddress);
                                        } else {
                                            Toast.makeText(H5Activity.this, "尚未安装腾讯地图", Toast.LENGTH_SHORT).show();
                                            Uri uri = Uri.parse("market://details?id="+MapUtil.PN_TENCENT_MAP);
                                            startActivity(new Intent(Intent.ACTION_VIEW, uri));
                                            break;
                                        }
                                }
                            }
                        }

                ).show();
    }

    @Override
    protected void onDestroy() {
        releaseWebViews();
        if (locationClient != null && locationClient.isStarted()) {
            locationClient.unRegisterLocationListener(this);
            locationClient.stopLocation();
            if (locationClient != null) {
                locationClient.onDestroy();
                locationClient = null;
            }
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == CameraCore.REQUEST_TAKE_PHOTO_CODE ||
                requestCode == CameraCore.REQUEST_TAKE_PHOTO_CROP_CODE ||
                requestCode == CameraCore.REQUEST_TAKE_PICTURE_CODE ||
                requestCode == CameraCore.REQUEST_TAKE_PICTURE_CROP_CODE ||
                requestCode == CameraCore.REQUEST_TAKE_CROP_CODE ||
                requestCode == CameraCore.REQUEST_HEIGHT ||
                requestCode == CameraCore.REQUEST_WIDTH) {
            cameraProxy.onResult(requestCode, resultCode, data);
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == FILE_CHOOSER_RESULT_CODE) {
                Uri result = null;
                if (data != null) {
                    result = data.getData();
                }
                if (this.valueCallback != null) {
                    valueCallback.onReceiveValue(result);
                    valueCallback = null;
                } else if (valuesCallback != null) {
                    valuesCallback.onReceiveValue(new Uri[]{result});
                    valuesCallback = null;
                }
            }
        }
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            HashMap<String, Double> pos = GPSUtils.delta(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            if (isOnce) {
                callH5("javascript:locationCallBack(" + pos.get("lon") + "," + pos.get("lat") + ",'" + aMapLocation.getAddress() + "')");
                isOnce = false;
            }
            if (isTrace) {
                callH5("javascript:locationChanged(" + pos.get("lon") + "," + pos.get("lat") + ",'" + aMapLocation.getAddress() + "')");
            } else {
                if (locationClient != null && locationClient.isStarted()) {
                    locationClient.unRegisterLocationListener(this);
                    locationClient.stopLocation();
                    if (locationClient != null) {
                        locationClient.onDestroy();
                        locationClient = null;
                    }
                }
            }
        }
    }

    @Override
    public void onSuccess(String filePaht) {
        File file = new File(capturePath);
        if (file.exists()) {
            new Thread() {
                public void run() {
                    try {
                        //NativeUtil.compressBitmap(capturePath, capturePath);
                        File cameraFile = new File(capturePath);
                        Uri result = Uri.fromFile(cameraFile);
                        capturePath = "";
                        if (valueCallback != null) {
                            valueCallback.onReceiveValue(result);
                            valueCallback = null;
                        } else if (valuesCallback != null) {
                            valuesCallback.onReceiveValue(new Uri[]{result});
                            valuesCallback = null;
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }.start();
        }
    }

    @Override
    public void onFail(String message) {

    }

    interface OnBackListener {

        void onBack();

    }

    private void callH5(final String js) {
        Log.d("HTTP", js);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                wvH5.loadUrl(js);
            }
        });
    }

    private class X5WebChromeClient extends WebChromeClient {

        /*** 视频播放相关的方法 **/

        @Override
        public View getVideoLoadingProgressView() {
            FrameLayout frameLayout = new FrameLayout(H5Activity.this);
            frameLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            return frameLayout;
        }

        @Override
        public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
            showCustomView(view, callback);
        }

        @Override
        public void onHideCustomView() {
            hideCustomView();
        }
    }

    /**
     * 视频全屏参数
     */
    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    private View customView;
    private FrameLayout fullscreenContainer;

    /**
     * 视频播放全屏
     **/
    private void showCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback.onCustomViewHidden();
            return;
        }

        this.getWindow().getDecorView();

        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        fullscreenContainer = new FullscreenHolder(H5Activity.this);
        fullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS);
        customView = view;
        setStatusBarVisibility(false);
        customViewCallback = callback;
    }

    /**
     * 隐藏视频全屏
     */
    private void hideCustomView() {
        if (customView == null) {
            return;
        }

        setStatusBarVisibility(true);
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(fullscreenContainer);
        fullscreenContainer = null;
        customView = null;
        customViewCallback.onCustomViewHidden();
        wvH5.setVisibility(View.VISIBLE);
    }

    /**
     * 全屏容器界面
     */
    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }
    }

    private void setStatusBarVisibility(boolean visible) {
        int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                /** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面 */
                if (customView != null) {
                    hideCustomView();
                } else if (wvH5.canGoBack()) {
                    wvH5.goBack();
                } else {
                    finish();
                }
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }
}
